package com.wn.class30.cotroller.weixin;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wn.class30.entity.AlipayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RequestMapping("/alipay/")
@RestController
public class AlipayController {
    // 应用ID,您的APPID，收款账号既是您的APPID对应支付宝账号
    public static String app_id = "2016102100729234";

    // 商户私钥，您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAABjaTTfn7HVmykzf70hLT6+mthvxnj7PvWKrUcB6ic2gI8R1egX/pb9342CVoKUHNdG2CQfKRdRgJUHAFRQj/Rt+B2mhiO2KwmL3s64VYLVvGXHrH1mIpYJKRcfgnHJPDO3wxQtJZOKKPGKJ4wNdGCNk69Nu5R37u0f6qK6aT6kFuI0Z4AIBFSwp4l8Zx1tPIb1qjGziRDkZNYmO7UGXkx4dIIU85T8eBiIgbaO4oK0GPC3M35/x4TjhgdW2fNqpy0npG/4D089gkQyfvMIhTNvtO8/GonsRIQEmy9F3IUAptYE6PlISvL+FHFZ2SW9VaJbD64+lb4moFR2ah2CtAgMBAAECggEAZBivVregCnv9az60U0JZ9JsCL4ql25L2Z5ogePzbWng9FwghcATWgA7r5iMnupr/st3Be2sgbmuhIva/rihNsb8TKsE9N5dOu347ypz2e70+5Pyu+0Fu0M8tTku3fMybD3p68BgHNYPxLE0AeffO/5QKybcphsUhZ2QTa89Ri1W1usl+XoX2cl3MGvN7nMkt+bDokwsBit78Rieakv19gyw92hoVTF5MfJPPIlmMzb5HdNxlPJuebKmzQU/hz0W6qh2d2khInTs4fHBzVjBMaXCmFJlYAQmICcwgZ0aUf8S8LnJZDlTcreqmfnbTFpyX4qj5PWYde/ubJZu+k7EFeQKBgQDTcdFAbcLbMc4ZKokVTbR01cvT6EVxzVeb1TmwE+vx5hDzoZ5Wmr36NgWFfv9wHA+pbZbXQKnJlNUVFQ8kqfyud5N8go8XsbR7m9R9bXcSO/Bv5Tyl62eIBgOwCKmaH/k/RbDxKVdEfpbWEULFv0q1JF0+YU//y9hEQYzSC0nTTwKBgQCa+PVuD0PwWek5N2VnU7UZHDO+gtlLg4ibM64paNKTDeZDWLFefAM9dYrtnuZHUN1u9Kqur8VzsssGGkGfuFCwd7+o6q5ArMtuOXAa6q8XVhNdoQpHld7N0rgBOo0Njzw+dGTpQWpjxUiQ50fR4k3oUfzjzqKpGtTs3GSRsaD9QwKBgEw0xTn3VTcy6Bjh364x50wEkgW5vO2bGGwtmTEAvRTd2lY0daC4/KdlOPA4KU/6jRp/SNIjmA3y+ikzAdYw/cTTi/BgDbp4bZfvPdJG1ZdYyvtJH2adRR8dK88SEC5gP7CyKWeBgtZI2YwlhG9I1mAazxBgejiy+yr+hQZe0yi5AoGALwmp1QIlKOrhc1BxIu+xZDG/MvAcbGM8L398OW1rnN73KTHehEM36Iuo4377fmH5FBiHRgZr9DYskWmeyY/0TdvK/MZepZrNFGOytzjMdFTYA+9BY4EF44s19omDDr6PFpXVm0cTt7zFzdWlYvtBkmZwT+UEUjemsU4j6GT17GkCgYEAu8dUTmlxSF+JZJm9TbkRNcQk7hKOAcz9w2BS1AcILtAZoVGvnW3Iz4l7ln2R8hDIAH89KaH0kyFMcY72eNRGKYmRKhJdCOk+FRl2E3iTl05qc0UVJSyMTeDD+k6qhJoF3oNWq4LauQg/XRxqL9KY+wqMbdTfhNj0hz/K13stSyI=";

    // 支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqWprmMxJnks9IZdognbilVqyx0XFSi0xwujCiWQntaQDVskaDcWOImx3QNryJggG0uBd47gzx4RDJMT6ooyEW/w34t6559w0F4evqAWudHgKMjTjbk85lIk7PiLujheFbaSHwkVPvp2w3nJEJTaFopkt7QVGc6g58A+rYB5YPAkdhhUV4Ve2nvAGvG9AMejPQdZE4gvLuxbBoWS3vUvSLnij5MdYEUIf7eK9BBZ/WHTwgMQBwf2l0maJEITV90G6ntiaYy2hK1/au+etWfqo/bga2a2wPvQ/uZLFsI5WA1PfTjsspQjTk8RpY0NmzaW2gEoTvfN2AMA1RbrqhmtOWQIDAQAB";

    // 服务器异步通知页面路径  需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
   public static String notify_url = "http://zhouhao1.ngrok2.xiaomiqiu.cn/alipay/notify";
    //  public static String notify_url = "http://wchuan.mynatapp.cc/alipay/notify";

    // 页面跳转同步通知页面路径 需http://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    public static String return_url = "http://zhouhao1.ngrok2.xiaomiqiu.cn/alipay/return";
    //   public static String return_url = "http://wchuan.mynatapp.cc/alipay/return";

    // 签名方式
    public static String sign_type = "RSA2";

    // 字符编码格式
    public static String charset = "utf-8";

    // 支付宝网关
    public static String gatewayUrL = "https://openapi.alipaydev.com/gateway.do";
    //
    public static String log_path = "C:\\";

    @GetMapping("pay")
    private String alipayPay(String total_amount) throws AlipayApiException {

        AlipayVo vo = new AlipayVo();
        //这里模拟了一个订单的id
        vo.setOut_trade_no(UUID.randomUUID().toString().replace("-", ""));
        vo.setTotal_amount(total_amount);
        vo.setSubject("测试付款商品A");
        //这个是固定的，沙箱默认就用这个参数
        vo.setProduct_code("FAST_INSTANT_TRADE_PAY");
        String json = JSON.toJSONString(vo);
        log.info("发起支付传参："+json);
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrL, app_id,
                merchant_private_key, "json", charset, alipay_public_key, sign_type);
        // 设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        alipayRequest.setBizContent(json);
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            log.info("result："+result);
        } catch (Exception e) {
            log.info("payerror" + result);
        }

        return result;
    }
    /**
     * @Description: 支付宝回调接口
     * @param out_trade_no 商户订单号
     * @param trade_no     支付宝交易凭证号
     * @param trade_status 交易状态
     * @return String
     * @throws AlipayApiException
     */
    @PostMapping("notify")
    private String alipayNotify(HttpServletRequest request, String out_trade_no, String trade_no, String trade_status)
            throws AlipayApiException {
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipay_public_key, charset, sign_type);
        } catch (AlipayApiException e) {
            log.info("notify 验证失败",e);
            // 验签发生异常,则直接返回失败
            return ("failed");
        }
        if (signVerified) {
            //处理你的业务逻辑，更细订单状态等
            return ("success");
        } else {
            log.info("验证失败,不去更新状态");
            return ("failed");
        }
    }
    /**
     * @Description: 支付宝回调接口
     * @param out_trade_no 商户订单号
     * @param trade_no     支付宝交易凭证号
     * @return String
     * @throws AlipayApiException
     */
    @GetMapping("return")
    private String alipayReturn(Map<String, String> params, HttpServletRequest request, String out_trade_no, String trade_no, String total_amount)
            throws AlipayApiException {
        System.out.println("支付成功-----------------------------------");
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                System.out.println(valueStr);
            }
            map.put(name, valueStr);
        }
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipay_public_key, charset, sign_type);
        } catch (AlipayApiException e) {
            log.info("支付宝回调异常", e);
            // 验签发生异常,则直接返回失败
            return ("--fail--");
        }
        if (signVerified) {
//            return "http://wchuan.mynatapp.cc/weixin/user/index.html";
            //支付完成后可以这么跳转到其他界面
//            return ("<a href='http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/wechatpay/cg.html'>支付成功页面</a>");
                System.out.println("支付成功-----------------------------------");
            return ("<a href='http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/wechatpay/cg.html'>支付成功页面</a>");

//            return request.getScheme()+"://"+ request.getServerName()+"/weixin/wechatpay/cg.html";
//            return ("--success--");
        } else {
            return ("fail");
        }
    }

}
